// tslint:disable
import { Component, OnInit, AfterViewInit, NgZone, ChangeDetectorRef } from "@angular/core";
import { ActivatedRoute, Router, NavigationEnd } from "@angular/router";
import { ViewChild, ElementRef } from "@angular/core";

import { IonContent, Platform } from "@ionic/angular";

import { SplashScreen } from "@ionic-native/splash-screen/ngx";

import { IonTabs } from "@ionic/angular";

import { AppGlobalService } from "./../shared/service/app-global.service";
import { PageModalService } from "./../shared/service/page-modal-service";
import { EventService } from "../shared/service/event.service";
import { HttpService } from "../shared/service/http.service";
declare let $: any;
declare var cordova;
declare var Totop;
declare var showLoading;
declare var completeLoading;
declare var wx;
@Component({
  selector: "app-tabs",
  templateUrl: "tabs.page.html",
  styleUrls: ["tabs.page.scss"],
})
export class TabsPage implements OnInit, AfterViewInit {
  constructor(
    private http: HttpService,
    private route: ActivatedRoute,
    private router: Router,
    public appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService,
    private ngZone: NgZone,
    private cd: ChangeDetectorRef,  // 强制更新检测
    private splashScreen: SplashScreen,
    private platform: Platform
  ) {
    this.eventService.eventEmit.on("remindPaymentOrder", (obj) => {
      if (obj !== null) {
        // 未登录不展示浮窗
        this.paymentOrder = localStorage.getItem('userId') !== null ? obj : null;
      } else {
        this.paymentOrder = null;
      }
    });
  }
  @ViewChild("ionTabs", null) tabs: IonTabs;
  @ViewChild(IonContent) content: IonContent;

  sessionId: string;
  appNavigation: any[];
  flag = "tab1";
  defaultIndex = -111;
  isClick = true;
  showRefresh = false;
  netState: any = ""; // 网络状态
  // 位置对象
  positionInfo: any = {};
  lastIndex = 1;
  appTypeCustom: any;
  paymentOrder: any;
  timer: any;
  isIonTabsDidChange = false;
  isApp = false;
  ngOnInit() {
    
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    // console.log("tabs init");
    this.addListener();
    // 以下二选一

    // web预览模式
    // this.preViewApp();
    // this.debugApp(532, "lj_t_"); // 蜂喔商户
    // this.debugApp(530, "lj_t_");    // 蜂喔app
    // this.debugApp(254, "js_p_"); // 调试 装修新列
    // this.debugApp(546, "ppw_t_"); // 铺铺旺测试
    // this.debugApp(545, "pxw_t_"); // 铺小旺测试
    // this.debugApp(236, "pxw_p_"); // 铺小旺
    // this.debugApp(238, "ppw_p_"); // 铺铺旺
    // this.debugApp(453, "js_p_"); // 蜂喔商户
    // this.debugApp(444, "lj_p_"); // 蜂喔
    // this.debugApp(395, "lj_p_"); // 蜂喔

    // 统一发布APP方法

    this.releaseApp(); // APP
    // this.releaseAppNew();// H5
    this.initUmeng();
    this.cleanDraft();
  }
  cleanDraft(){
    const update = new Date().getTime();
    // 
    const arr = Object.keys(localStorage)
    let arrKey = [];
    arr.forEach(element => {
      if(element.indexOf("saveDraft:") > -1) {
        if(localStorage.getItem(element)){
          const obj = JSON.parse(localStorage.getItem(element));
          if (update - Number(obj.time) > 7 * 24 * 3600*1000){
            console.log('over 7*24H remove:' + element)
            arrKey.push(element);
            
          }
        }
         
      }
    });
    if (arrKey.length){
      arrKey.forEach(element => {
        localStorage.removeItem(element)
      });
    }
    
    // if (that.hintId == undefined || update - Number(that.hintId.split('hintId')[1]) < 1000 ) {
    //   console.log("not need updateFrom " + (update - Number(that.hintId.split('hintId')[1])));
    //     return;
    // }
  }
  
  addListener() {

    

    if (this.eventService.eventEmit.listenerCount("bindWeChatLoginCode") > 0) {
      this.eventService.eventEmit.removeListener("bindWeChatLoginCode");
    }
  
    this.eventService.eventEmit.on("bindWeChatLoginCode", (data) => {
       // 与微信绑定
       if (this.appGlobalService.wxLoginCode) {
        this.http.bindWeChatLoginCode(success => {
          if(localStorage.getItem('loginAccount') === "19168928480"){
            alert('wxlogincode bind:' + success);
          }
          
        });
      }
    });
    
    if (this.eventService.eventEmit.listenerCount("selectTabsByIndex") > 0) {
      this.eventService.eventEmit.removeListener("selectTabsByIndex");
    }
    // add by andrew.wen for 刷新指定tabs
    this.eventService.eventEmit.on("selectTabsByIndex", (data) => {
      if (localStorage.getItem("selectTabsByIndexTag")) {
        const selectStr = localStorage.getItem("selectTabsByIndexTag");
        localStorage.removeItem("selectTabsByIndexTag");
        this.tabs.select(selectStr);
      }
    });

    if (localStorage.getItem("position") === null) {
      // add by andrew.wen 此处需要默认给个中心点的坐标，否则不允许定位的手机不会获取到统计信息。
      const position = {
        name: this.appGlobalService.defaultCityName,
        code: this.appGlobalService.defaultCityId,
        center: this.appGlobalService.defaultCityCenter,
        districtCode:this.appGlobalService.defaultDistrictCode
      };
      // if (this.platform.is('android')) {
      //   if (!localStorage.getItem('alreadyAllowPhysicalLocation')) {
      //     // todo position 
      //     position.name = "获取位置";
      //   }
      // }
      localStorage.setItem("position", JSON.stringify(position));
      localStorage.setItem("currentCityPosition", JSON.stringify(position));
    }
  }
  initUmeng() {
    this.appGlobalService.initUmengEventWithParameters("enter_app_with_Event");
  }
  // 处理 客户、员工 当前定位城市
  setCityPosition() {
    console.log("setCityPosition-----");
    // 触发拿 第一次城市信息
    if (this.appGlobalService.clientType === "ppw") {
      const firstPostion = localStorage.getItem("firstPostion");
      if (!firstPostion) {
        localStorage.setItem("firstPostion", localStorage.getItem("position"));
      }
    }
  }

  // web预览模式
  preViewApp() {
    this.appGlobalService.isPreview = true;
    this.route.queryParams.subscribe((params) => {
      this.sessionId = params.sessionId;
      if (!this.sessionId) {
        this.sessionId = localStorage.getItem("sessionId");
      }
      localStorage.setItem("sessionId", this.sessionId);
    });

    let webglHash = this.eventService.getUuid();

    if (this.sessionId && this.sessionId !== "null") {
      const params = {
        sessionId: this.sessionId,
        deviceId:  webglHash, 
        keyCode: webglHash, 
        phoneType: localStorage.getItem('platform') === 'ios' ? 1 : 0,
        cityId: this.positionInfo.code,
      };
      // 请求获取新数据
      console.log("preViewApp getting app tab data \n");
      this.http.post("application/home/", params, (res) => {
        // 请求数据成功
        if (res) {
          this.getPageData(res);
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
      });
    } else {
      console.log("无法获取sessionId");
    }
  }

  // if change projectId , use new sessionId if projectId == -100 show Message
  checkProject(target, version, callback) {
    const that = this;
    if (target) {
      this.http.get(
        "application/getProjectId/xw/" + version,
        (res) => {
          if (res.projectId && res.projectId === "-100") {
            localStorage.setItem("projectId", res.projectId);
            this.appGlobalService.showToast(res.message, 3000, "middle");
            callback(false);
          } else if (
            res.projectId && localStorage.getItem("projectId") !== res.projectId
          ) {
            localStorage.setItem("projectId", res.projectId);
            // 当是微信小程序传来的session 时 不重新请求新的session，前提是 不带参数的session接口 与 最新code对应的session指向同一个项目id，在铺铺旺最新App 审核通过后在更新小程序
            if (localStorage.getItem("sessionIdFromWX") === "true") {
              callback(false);
            } else {
              callback(true);
            }
          } else {
            callback(false);
          }
        },
        (err) => {
          callback(false);
        }
      );
    } else {
      callback(false);
    }
  }

  /** 打包测试 116 是测试项目 id */
  debugApp(pId?, pushAlias?) {
    const that = this;
    if (pId) {
      this.appGlobalService.debugAppId = pId;
    }
    if (pushAlias) {
      this.appGlobalService.pushAlias = pushAlias;
    }
    if (
      localStorage.getItem("sessionId") !== null && localStorage.getItem("sessionId") !== "null" &&
      localStorage.getItem("sessionId") !== undefined
    ) {

      this.sessionId = localStorage.getItem("sessionId");
      let webglHash = this.eventService.getUuid();
      const params = {
        sessionId: this.sessionId,
        deviceId: webglHash,
        keyCode: webglHash, // 浏览器指纹参数
        phoneType: localStorage.getItem('platform') === 'ios' ? 1 : 0,
        cityId: this.positionInfo.code
      };
      console.log("上次session-----", this.sessionId);
      this.http.post(
        "application/home/",
        params,
        (res) => {
          this.getPageData(res);
        },
        (error) => {
          // 处理因home接口session过期而导致的白屏问题
          if (error && error.code === "5502") {
            // 如已经重新请求过sessionId 则不在请求，显示错误页面可以点击刷新 重新请求
            if (localStorage.getItem("reGetSession")) {
              that.getNetState();
            } else {
              that.http.getSession(
                (session) => {
                  localStorage.setItem("reGetSession", "true");
                  that.debugApp(
                    this.appGlobalService.debugAppId,
                    this.appGlobalService.pushAlias
                  );
                },
                (err) => {
                  that.getNetState();
                }
              );
            }
          } else {
            // home fail
            that.getNetState();
          }
        }
      );
    } else {
      that.debugAppGetNewSessionId();
    }
  }

  debugAppGetNewSessionId() {
    const that = this;
    localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
    this.http.get(
      "application/debug/" + this.appGlobalService.debugAppId,
      (ress) => {
        this.sessionId = ress.sessionId;
        localStorage.setItem("sessionId", this.sessionId);
        console.log(this.sessionId);
        that.debugApp();
      },
      (err) => {
        that.getNetState();
      }
    );
  }
  // 发布
  releaseApp() {
    
    // if(this.appGlobalService.clientType === 'lj'){
      const that = this;
      this.platform.ready().then(()=>{
        this.isApp = true; //  打包APP 打开注释
        console.log('msg----->tabs.page.ts' + new Date().getMilliseconds());
        console.log('msg----->tabs.page.ts' + (typeof Totop));
        // ios 第一次等待网络授权 没有请求成功过api就认为没授权过，
        const ua = window.navigator.userAgent;
        console.log('ua:' + ua);
        let os: any;
        if (this.isApp && ua.indexOf('iPhone OS') > -1) {
          const index = ua.indexOf('iPhone OS');
          os = ua.substring(index + 10, index + 12);
          console.log('ios:' + os);
        }
        // const that = this;
        if (os && Number(os) >= 15 && (localStorage.getItem('firstInstallIOS') === undefined || localStorage.getItem('firstInstallIOS') === null)) {
          this.showRefresh = true;
          this.netState = "wait ios net";
  
          console.log('wait iOS---Totop-->tabs.page.ts' + (typeof Totop));
          if ((typeof Totop) !== 'undefined') {
  
            let hasSendNet = false; // 会回调2次
            Totop.iosNetworkState('wait ios net', success => {
              console.log("ToTop ios network status success :" + success);
  
              if (success === 'wait net') {
                // this.netState = "wait ios net";
                
              } else if (success === 'allow net') {
                localStorage.setItem('firstInstallIOS', "2");
                setTimeout(() => {
                  window.location.reload();  
                }, 50);
                
              } else {
                if (!hasSendNet) {
                  if(this.content){
                    this.content.scrollByPoint(0, 1, 50);
                    this.content.scrollToTop();
                  }
                  hasSendNet = true;
                  this.releaseAppNew();
                }
  
              }
  
            }, error => {
              console.log("test iosNetworkState error :" + error);
              this.releaseAppNew();
  
            });
          } else {
            this.releaseAppNew();
            console.log('msg-----> Totop fail~~' + new Date().getMilliseconds());
  
          }
        } else {
          if (!(this.appGlobalService.clientType === 'js' && localStorage.getItem('loginStatus')!=='true')) {
            // 商户没有登录不加载tab缓存
            if(localStorage.getItem('homeData')) {
              console.log('tabs use last HomeData platform.ready() 1');
              that.getPageData(JSON.parse(localStorage.getItem('homeData') as string),true);
            } else {
              console.log('tabs use local HomeData platform.ready() 1');
              that.getPageData(that.localData(),true);
            }
          } 
          
  
          this.releaseAppNew();
          console.log('msg----->not ios' + new Date().getMilliseconds());
        }
        
      });

  }
  
  refreshPageNew(){
    window.location.reload();
  }
  releaseAppNew() {
    // 版本更新重新请求一次session
    this.checkAppVersion();
    const that = this;
    if(localStorage.getItem("Code") != undefined){
      this.appGlobalService.ReleaseVersionCode =  1000;
      localStorage.removeItem("Code")
    }    
    this.appGlobalService.getSessionPath = "application/openApp/xw/" + this.appGlobalService.ReleaseVersionCode;
    this.checkProject("xw", this.appGlobalService.ReleaseVersionCode, (res) => {
      if (res) {
        localStorage.removeItem("sessionId");
        that.releaseAppGetNewSessionId();
      } else {
        if (localStorage.getItem("sessionId")) {
          this.sessionId = localStorage.getItem("sessionId");
          console.log("上次session-----", this.sessionId);
          that.getHomePage();
        } else {
          that.releaseAppGetNewSessionId();
        }
      }
    });
  }
  getHomePage(callback?: Function, error?: Function) {
    const that = this;
    let params: any = {
      sessionId: this.sessionId
    };

   
    let webglHash = this.eventService.getUuid();
    let cancelLoading = false;
    if(localStorage.getItem('loginStatus')!=='true' && this.appGlobalService.clientType === 'js' ){
      cancelLoading = false
    } else {
      cancelLoading = true
      console.log('tabs home page 使用缓存数据不显示loading!!!');
    }
    
    params = {
      sessionId: this.sessionId,
      deviceId: webglHash, // ios idfa or androidid
      keyCode: webglHash, // 
      phoneType: localStorage.getItem('platform') === 'ios' ? 1 : 0 ,
      cityId: this.positionInfo.code,
      cancelLoading:cancelLoading // 使用缓存时不loading
    };
    if(localStorage.getItem('sharer_user')){
      this.appGlobalService['sharer_user'] = localStorage.getItem('sharer_user')
    }
    this.appGlobalService.consoleLog('sharer_user', window.location.href);
    if (window.location.href.indexOf('sharer_user') > -1) {
      let uid = this.appGlobalService.getUrlParamsByName(window.location.href, 'sharer_user');
      if (uid !== undefined) {
        this.appGlobalService.consoleLog('uid ===', uid);
        params['params'] = { sharer_user: uid };
        this.appGlobalService.consoleLog('home 请求参数=', params);
      }
    }
    // 2024.10.29 for home api add test parameters
    if(this.appGlobalService['test']){
      params['params']['test'] = this.appGlobalService['test'];
      this.appGlobalService.consoleLog('for home api add test parameters', '  	   ');
    }
    
    // }
    // alert('keyCode:' + localStorage.getItem('keyCode'));
    this.http.post("application/home/", params, (res: any) => {
      this.getPageData(res);
    }, (error) => {
      // 处理因home接口session过期而导致的白屏问题
      if (error && error.code === "5502") {
        // 如已经重新请求过sessionId 则不在请求，显示错误页面可以点击刷新 重新请求
        if (localStorage.getItem("reGetSession")) {
          that.getNetState();
        } else {
          that.http.getSession(
            (session) => {
              localStorage.setItem("reGetSession", "true");
              console.log('get the new session req home page！！')
              this.sessionId = session;
              this.getHomePage();
              // that.releaseAppNew();
            },
            (err) => {
              that.getNetState();
            }
          );
        }
      } else {
        // home 失败刷新
        that.getNetState();
      }
    }
    );
  }


  releaseAppGetNewSessionId() {
    const that = this;
    localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
    this.http.get(
      "application/openApp/xw/" + this.appGlobalService.ReleaseVersionCode,
      (ress) => {
        this.sessionId = ress.sessionId;
        localStorage.setItem("sessionId", this.sessionId);
        that.getHomePage();
      },
      (err) => {
        // 处理因session接口失败的白屏问题 刷新
        that.getNetState();
      }
    );
  }

  // App
  getPageData(res,isCache?) {
    // this.showRefresh = false;
    this.ngZone.runOutsideAngular(() => {
      this.ngZone.run(() => {
        this.showRefresh = false;
      });
    });
    if (res) {
      if(!isCache){
        localStorage.setItem('homeData',JSON.stringify(res));
        localStorage.setItem('firstInstallIOS', "2");

      }
      const pageData = JSON.parse(res.script);
      this.appGlobalService.clientType = pageData.clientType;
      this.setCityPosition();
      this.appNavigation =
        JSON.stringify(pageData.navgtion) !== "{}" ? pageData.navgtion : false;
      localStorage.setItem("appNav", JSON.stringify(this.appNavigation));
      if(isCache){
        this.eventService.eventEmit.emit("appNav", "0");
      } else {
        this.eventService.eventEmit.emit("appNav", "1");
      }
      
      // 预览需要手动控制路由跳转一次
      if (this.appGlobalService.isPreview) {
        for (let i = 0; i < this.appNavigation.length; i++) {
          if (this.appNavigation[i].check) {
            console.log("defaul index ===== ", i, this.appNavigation[i].label);
            this.defaultIndex = i;
            this.getDefaultPageData(
              this.defaultIndex + 1,
              +this.appNavigation[this.defaultIndex].target
            );
            break;
          }
        }

        if (this.defaultIndex === -111) {
          this.defaultIndex = 0;
          this.getDefaultPageData(
            this.defaultIndex + 1,
            +this.appNavigation[this.defaultIndex].target
          );
        }
      }
     
    }
    // if (this.appGlobalService.clientType === "ppw" || this.appGlobalService.clientType === "lj" || this.appGlobalService.clientType === "js") {
    //   //2.0 遵循安卓隐私权策略处理方法，安卓不直接获取定位
    //   if (!this.platform.is('android')) {
    //     this.mapBaiduService.refreshWatchPosition(() => {
    //       this.ngZone.runOutsideAngular(() => {
    //         this.ngZone.run(() => {
    //           this.eventService.emit("getLocationDone", "true");
    //         });
    //       });
    //     });
    //   }
    // }
  }

  getDefaultPageData(index, viewId) {
    const path = "home/tab" + index;
    console.log("preview ============================default path", path);
    localStorage.setItem("tabPath", path);
    // this.router.navigate([path], { queryParams: { viewId } });
    this.router.navigate([path]);
  }

  change(event) {
    this.appGlobalService.openBackdrop = false;
    this.isIonTabsDidChange = true;
    this.flag = event.tab; // event.detail.tab;
    if (this.flag) {
      const path = "home/" + this.flag;
      console.log("===================================default path", path);
      localStorage.setItem("tabPath", path);

      // tab1ScrollToTop2 文字替换为首页    tab1ScrollToTop3 文字替换为回顶部
      if (this.flag === "tab1" && this.appGlobalService.homePageScrollTop > 252) {
        setTimeout(() => {
          this.eventService.emit("tab1ScrollToTop3", '1');
        }, 1);
      } else if (this.appGlobalService.homePageToTop) {
        this.eventService.emit("tab1ScrollToTop2", false);
      }
    }
  }

  // 减逻辑
  setBadgeForKeyValue(key, num) {
    const index = +key.substring(key.length - 1) - 1;
    const item = this.appNavigation[index];
    const badge = +(item.badge - num);
    item.badge = badge;
    if (badge <= 0) {
      item.badge = 0;
    }
  }

  setMsgBadgeValue(key, num) {
    const index = +key.substring(key.length - 1) - 1;
    const item = this.appNavigation[index];
    if (item.badge === undefined) {
      item.badge = 0;
    }
    const badge = +(item.badge + num);
    if (badge <= 0) {
      item.badge = 0;
    }
    item.badge = badge;
  }

  reduceBadgeValue(key, num) {
    const index = +key.substring(key.length - 1) - 1;
    const item = this.appNavigation[index];
    if (item.badge === undefined) {
      item.badge = item.badge + num;
    }
  }

  // 设置初始值
  firstBadgeForKeyValue(key, num) {
    const index = +key.substring(key.length - 1) - 1;
    const item = this.appNavigation[index];
    item.badge = num;
    if (num <= 0) {
      item.badge = 0;
    }
  }
  ngAfterViewInit(): void {
    // obj 结构{tab1:10}
    this.eventService.eventEmit.on("badgeForTab", (obj) => {
      let key = "";
      if (obj.tab1 >= 0) {
        key = "tab1";
        this.setBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab2 >= 0) {
        key = "tab2";
        this.setBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab3 >= 0) {
        key = "tab3";
        this.setBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab4 >= 0) {
        key = "tab4";
        this.setBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab5 >= 0) {
        key = "tab5";
        this.setBadgeForKeyValue(key, obj[key]);
      }
    });
    // 更新红点信息
    this.eventService.eventEmit.on("updateMsgBadge", (obj) => {
      if (localStorage.getItem("isUpdateMsgBadgeTag")) {
        localStorage.removeItem("isUpdateMsgBadgeTag");
        let key = "";
        if (obj.tab3 >= 0) {
          key = "tab3";
          this.updateTabMessageBadge("spanBadge");
          this.setMsgBadgeValue(key, obj[key]);
        } else if (obj.tab2 >= 0) {
          key = "tab2";
          this.updateTabMessageBadge("spanBadge", "TAB2");
          this.setMsgBadgeValue(key, obj[key]);
        } else if (obj.tab2 < 0) {
          key = "tab2";
          this.reduceBadgeValue(key, obj[key]);
        } else if (obj.tab3 < 0) {
          key = "tab3";
          this.reduceBadgeValue(key, obj[key]);
        }

      }
    });
    // 清除红点信息
    this.eventService.eventEmit.on("initMsgBadge", (obj) => {
      if (localStorage.getItem("isInitMsgBadgeTag")) {
        localStorage.removeItem("isInitMsgBadgeTag");
        this.updateTabMessageBadge();
      }
    });
    this.eventService.eventEmit.on("firstBadgeForTab", (obj) => {
      let key = "";
      if (obj.tab1 >= 0) {
        key = "tab1";
        this.firstBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab2 >= 0) {
        key = "tab2";
        this.firstBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab3 >= 0) {
        key = "tab3";
        this.firstBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab4 >= 0) {
        key = "tab4";
        this.firstBadgeForKeyValue(key, obj[key]);
      }
      if (obj.tab5 >= 0) {
        key = "tab5";
        this.firstBadgeForKeyValue(key, obj[key]);
      }
    });
  }


  // 更新tab3 消息红点
  updateTabMessageBadge(className?, indexStr?) {
    // 需要判断当前是在tab1~tab5 还是nav add by andrew.wen
    const ionRouterOutlet = document.getElementsByTagName("ion-router-outlet");
    if (ionRouterOutlet && ionRouterOutlet[1]) {
      try {
        const tabTtmlCollection = ionRouterOutlet[1];
        const len = tabTtmlCollection.children.length;
        let indexOfStr = "TAB3";
        if (indexStr) {
          indexOfStr = indexStr;
        }
        for (let i = 0; i < len; i++) {
          const nodeName = String(tabTtmlCollection.children[i].nodeName);
          if (nodeName.indexOf(indexOfStr) > -1) {
            const tempTabObj = tabTtmlCollection.children[i];
            const tmp = tempTabObj.children[0].children[1].children[0]
              .children[1] as HTMLElement;
            this.appGlobalService.invitationMsgBdge = className ? true : false;
            tmp.className = className ? className : "";
            break;
          }
        }
      } catch (e) {
        console.log("msg----->," + JSON.stringify(e));
      }
    }
  }

  refreshPage() {

    clearTimeout(this.timer)
    const that = this;
    this.timer = setTimeout(() => {
      showLoading();
      if (
        that.appGlobalService.getSessionPath ===
        "application/openApp/xw/" + that.appGlobalService.ReleaseVersionCode
      ) {
        that.refreshPageNew()
      } else {
        that.debugApp();
      }
    }, 200);

  }
  getNetState() {
    if (localStorage.getItem("netState") === "No network connection") {
      this.netState = localStorage.getItem("netState");
    } else {
      this.netState = "";
    }
    this.showRefresh = true;
    // 清除sessionId
    localStorage.removeItem("sessionId");
    localStorage.removeItem("reGetSession");
    this.splashScreen.hide();
  }
  backdropclick() {
    this.appGlobalService.openBackdrop = false;
  }

  checkAppVersion() {

    if (localStorage.getItem('appVersion') !== this.appGlobalService.appVersion) {
      localStorage.removeItem('sessionId');
      localStorage.setItem('appVersion', this.appGlobalService.appVersion);
      console.log('newVersion remove sessionId');
      this.appGlobalService.clearALLCacheData('cache',res =>{
        if(res != "-1"){
        }
      });    
   }
  }

  gotoPage(link) {
    this.pageModalService.openPage(link);
  }

  fadeClose() {
    $('#unpaidOrdersId').fadeOut();
  }

  tabsWillChange(event, tab) {
    if (tab !== undefined) {
      if (tab.type !== undefined && tab.type === 'page') {
        const link = {
          target: tab.target,
          params: tab.params,
          type: tab.type
        };
        this.pageModalService.openPage(link);
      }
    }
  }
  getNgStyle(value) {
    if (value) {
      const cssStyles = value.split(";");
      const newStyle = {};
      for (let i = 0; i < cssStyles.length; i++) {
        const cssStrs = cssStyles[i].split(":");
        newStyle[cssStrs[0]] = cssStrs[1];
      }
      return newStyle;
    }
  }



  goTop(e) {
    if (this.appGlobalService.homePageToTop === true && this.flag === 'tab1' &&  this.isIonTabsDidChange === false) {
      this.eventService.emit("tab1ScrollToTop2", true);
    } else {
      this.isIonTabsDidChange = false;
    }
  }

  openNetSetting() {
    if (cordova && cordova.plugins.settings) {
      console.log('openNativeSettingsTest is active');
      cordova.plugins.settings.open("network", () => {
        console.log('opened settings');
      },
        () => {
          console.log('failed to open settings');
        }
      );
    } else {
      console.log('openNativeSettingsTest is not active!');
    }
  }
  localData(){
    if(this.appGlobalService.clientType === 'lj'){
      return {
        code: null, message: null, projectId: null,
        script: 
        "{\"type\":\"page\",\"style\":\"page.FramePageLogic\",\"clientType\":\"lj\",\"navgtion\":[{\"normalIco\":\"lj_tabbar_icon_home_nor@3x.png\",\"ifuser\":true,\"check\":true,\"label\":\"首页\",\"params\":{\"opp_id2\":\"1111\",\"opp_id\":\"1111\",\"recommendTab\":\"0\",\"indexTab\":\"0\",\"opp_id3\":\"1111\",\"order\":\"\"},\"selectedIco\":\"lj_tabbar_icon_home_pre.gif\",\"target\":\"190058\",\"order\":\"1\"},{\"normalIco\":\"lj_tabbar_icon_open a shop_nor@3x.png\",\"ifuser\":true,\"check\":false,\"label\":\"入驻\",\"params\":{\"base_info_id\":\" \",\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_open a shop_pre.gif\",\"target\":\"190471\",\"order\":\"2\"},{\"normalIco\":\"width:20vw\",\"ifuser\":true,\"check\":false,\"label\":\"\",\"type\":\"page\",\"params\":{\"type\":\"publish_opp\",\"plugin_id\":\"4000\",\"base_info_id\":\" \",\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_release_pre.gif\",\"target\":\"190470\",\"order\":\"3\"},{\"normalIco\":\"lj_tabbar_icon_new_nor@3x.png\",\"ifuser\":true,\"check\":false,\"label\":\"消息\",\"params\":{\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_new_pre.gif\",\"target\":\"190021\",\"order\":\"4\"},{\"normalIco\":\"lj_tabbar_icon_my_nor@3x.png\",\"ifuser\":true,\"check\":false,\"label\":\"我的\",\"params\":{\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_my_pre.gif\",\"target\":\"190536\",\"order\":\"5\"}]}"
      }
    } else if(this.appGlobalService.clientType === 'js' && localStorage.getItem('loginStatus')==='true'){
      
      return {
        "script": "{\"type\":\"page\",\"style\":\"page.FramePageLogic\",\"clientType\":\"js\",\"navgtion\":[{\"normalIco\":\"lj_tabbar_icon_home_nor@3x.png\",\"ifuser\":true,\"check\":true,\"label\":\"首页\",\"params\":{\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_home_pre@3x.png\",\"target\":155198,\"order\":\"1\"},{\"normalIco\":\"lj_tabbar_icon_new_nor@3x.png\",\"ifuser\":true,\"check\":false,\"label\":\"消息\",\"params\":{\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_new_pre@3x.png\",\"target\":\"154922\",\"order\":\"2\"},{\"normalIco\":\"lj_tabbar_icon_my_nor@3x.png\",\"ifuser\":true,\"check\":false,\"label\":\"管理\",\"params\":{\"noUseCache\":true},\"selectedIco\":\"lj_tabbar_icon_my_pre@3x.png\",\"target\":\"153803\",\"order\":\"3\"}]}",

        "projectId": null,
        "message": null,
        "code": null
      }
    }
    
  }
}
